/**
 * Created by Administrator on 2017/2/25.
 */
const express = require('express'),
      bodyParser = require('body-parser'),
      cookieParser = require('cookie-parser'),
        settings = require('./settings'),
        flash = require('connect-flash'),
        session = require('express-session'),
        MongoStore = require('connect-mongo')(session);

const routes = require('./routes/index');
const app = express()

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));

app.use(express.static('../www'))
app.use(flash());
app.use(cookieParser());
app.use(session({
  //防止篡改cookie
  secret:settings.cookieSecret,
  //设置值
  key:settings.db,
  //cookie的生存周期
  cookie:{maxAge:1000*60*60*24*30},
  //将session的信息存储到数据库当中去.避免session因为各种原因丢失
  //真实的项目会放到redis或者memcached里面去---放在内存里(cpu里读取速度快)
  //但是----mongodb放在硬盘里面
  store: new MongoStore({
    //连接数据库当中的blog数据库
    url: 'mongodb://localhost/blog'
  }),
  resave:false,
  saveUninitialized:true
}));

app.use(function(req,res,next){
  res.locals.user = req.session.user;
  res.locals.success = req.flash('success').toString();
  res.locals.error = req.flash('error').toString();
  next()
})

app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", ' 3.2.1')
  if (req.method == "OPTIONS") res.send(200);/*让options请求快速返回*/
  else next();
})
routes(app)
app.get('/',function(req,res){

})


app.listen(3000,function(){
  console.log('server is running')
})


module.exports = app;
